package com.tingyuge.base.thread.tools;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Created by xiaodao
 * date: 2020/3/23
 */
public class SemaphreDemo {

    public static void main(String[] args) throws InterruptedException {
        //传入票据.
        Semaphore semaphore = new Semaphore(2);
        for (int i = 0; i <10 ; i++) {
            new Thread(new Task(semaphore,"zqp--"+i)).start();

        }
    }
    static class Task extends Thread{
        Semaphore semaphore;


        public Task(Semaphore semaphore,String name){
            this.semaphore = semaphore;
            this.setName(name);

        }

        @Override
        public void run() {

            try {
                semaphore.acquire();
                System.out.println("获取到线程: " + Thread.currentThread().getName() +" 时间: "+ System.currentTimeMillis());
                TimeUnit.SECONDS.sleep(1);
//                System.out.println("释放到线程: " + Thread.currentThread().getName() +" 时间: "+ System.currentTimeMillis());
                semaphore.release();
                System.out.println();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
    }
}
